<template>
	<view>
		<view class="page page-bottom-bar book-hotel">
			<!-- 入住信息 -->
			<view class="book-info p25">
				<view class="font15">{{billInfo.hotel ? billInfo.hotel.name : ''}}</view>
				<view class="font13">
					<image class="icon-date" mode="widthFix" src="https://static.newbeaconhotels.com/app/hotel/icon-date.png"></image>
					<text class="font-969696">入住：</text>
					<uni-dateformat class="format" :date="calendar.startDate" format="yyyy-MM-dd"></uni-dateformat>
					<text class="font12 font-969696">{{billInfo.hotel.msg}}可入住</text>
				</view>
				<view class="font13 font-969696">
					<image class="icon-lan" mode="widthFix" src="https://static.newbeaconhotels.com/app/hotel/icon-lan.png"></image>
					<text>{{billInfo.hotel ? billInfo.hotel.addrd : ''}}</text>
				</view>
			</view>
			<view class="hr7"></view>
			<!-- 订单信息 -->
			<view class="book-detail font14">
				<view class="item">
					<view>{{roomName}}</view>
					<view>1 间</view>
				</view>
				<view class="item" @click="Onman">
					<view>入住人</view>
					<view>{{form.rsvman}}　{{form.mobile}}<uni-icons type="arrowright" size="10" color="#3f3f3f"></uni-icons></view>
				</view>
				<view class="item">
					<view>到店时间</view>
					<view class="flex-1 tr">
						<biaofun-datetime-picker
							placeholder="请选择到店时间"
							:start="time.start"
							:end="time.end"
							fields="minute"
							@change="Ontime"
						></biaofun-datetime-picker>
					</view>
					<uni-icons type="arrowright" size="10" color="#3f3f3f"></uni-icons>
				</view>
				<view class="item nob">
					<view>支付方式</view>
					<uni-data-checkbox
						v-model="payType.value"
						:localdata="payType.range"
						:selectedColor="themeColor"
						selectedTextColor="#1e1e1e"
						@change="payChange">
					</uni-data-checkbox>
				</view>
				<view class="item" @tap="openCoupon">
					<view>优惠券</view>
					<view :style="{color: coupon.selected ? '#1e1e1e' : (billInfo.coupon ? '#ff0000' : '#c8c8c8')}">
						<text>{{coupon.selected ? ('-￥' + coupon.selected.reduce_money) : (billInfo.coupon ? billInfo.coupon + '张优惠券可用' : '无可用优惠券')}}</text>
						<uni-icons type="arrowright" size="10" color="#3f3f3f"></uni-icons>
					</view>
				</view>
			</view>
			<view class="hr7"></view>
			<!-- 发票信息 -->
			<view class="book-memo p25">
				<view class="font12 font-assist">*发票信息 如需办理发票，可去前台办理</view>
				<textarea :value="form.remark" @input="Onremark" placeholder="请输入备注内容" placeholder-class="placeholderClass"></textarea>
			</view>
			<view class="hr7"></view>
			<!-- 说明 -->
			<view class="book-tip p25">
				<view class="font13 font-646464">说明：</view>
				<view class="nodes font11 font-646464">
					<rich-text :nodes="billInfo.hotel ? billInfo.hotel.explain : ''"></rich-text>
				</view>
			</view>
		</view>
		
		<!-- 优惠券弹窗 -->
		<bottomPopup ref="coupon" title="选择优惠券" :btnMargin="'60rpx auto;'">
			<scroll-view :scroll-y="true" v-if="coupon.list && coupon.list.length > 0" class="popup-coupons">
				<view class="coupon-item flex-row-start" v-for="(item, index) in coupon.list" :key="index">
					<view class="left flex-column-center">
						<view class="tag">{{item.coupon_type_name}}</view>
						<view class="font12 font-assist">
							<!-- 10满减卷 30立即卷 -->
							<text v-if="item.coupon_type==10 || item.coupon_type==30">￥</text>
							<text v-if="item.coupon_type==10 || item.coupon_type==30" class="dis">{{item.reduce_money}}</text>
							<!-- 20折扣卷 -->
							<text v-if="item.coupon_type==20" class="dis">{{item.discount*10}}折</text>
						</view>
					</view>
					<view class="right flex-column-between">
						<view class="font13">{{item.title}}</view>
						<!-- 10满减卷 -->
						<view v-if="item.coupon_type==10" class="font12 font-assist">满{{item.full_money}}使用</view>
						<!-- 20折扣卷 30立即卷 -->
						<view v-if="item.coupon_type==20 || item.coupon_type==30" class="font12 font-assist">无限制</view>
						<view class="font12 font-969696">有效期至{{item.end_time}}</view>
					</view>
					<view @click="Onreduce(item)" class="get font12 font-ffffff tc">{{ item.choois ? '取消使用' : '立即使用'}}</view>
				</view>
			</scroll-view>
			<view v-else class="content coupon-empty">
				<image class="img" src="https://static.newbeaconhotels.com/app/hotel/empty.png"></image>
				<view class="txt font13 font-969696 tc">暂无优惠券</view>
			</view>
		</bottomPopup>
		
		<!-- 合计信息 -->
		<view class="book-bar flex-row-between flex-start">
			<view class="part1 flex-column-center flex-start">
				<view class="font12">订单金额: <text class="font16 font-assist">￥{{coupon.selected ? c_total : billInfo.total}}</text></view>
				<view class="font11 font-assist">已优惠￥{{billInfo.discount}}</view>
			</view>
			<view class="part2" @tap="openDetails">
				<text class="font11">明细</text>
				<uni-icons type="arrowup" size="10" color="#424141"></uni-icons>
			</view>
			<view class="btn tc font15 font-ffffff" @click="submit">提交订单</view>
		</view>
		
		<!-- 订单明细 -->
		<bottomPopup ref="details" title="订单明细">
			<view class="details-box">
				<view v-if="billInfo.price" class="list">
					<block v-for="(item, index) in billInfo.price.daily" :key="index">
						<view class="flex-row-between font14 font-969696">
							<view class="">{{item.date}}</view>
							<view class="">￥{{item.realRate}}</view>
						</view>
					</block>
				</view>
				<view class="price font14 font-969696">
					<view class="">优惠金额：<text class="font-assist">￥{{billInfo.discount}}</text></view>
					<view class="">订单合计：<text class="font-assist">￥{{coupon.selected ? c_total : billInfo.total}}</text></view>
				</view>
			</view>
		</bottomPopup>
		
		<!-- 确认弹窗 -->
		<uni-popup ref="confirm" type="center">
			<view class="popup-prize">
				<view class="title font15 tc font-b">订单确认</view>
				<view class="content">
					<view class="font14 font-ff3c37 tc">
						<text>卡类型：时租房；</text>
						<text>订单总额：￥{{coupon.selected ? c_total : billInfo.total}}</text>
					</view>
					<view class="font12 font-969696">在线支付订单整晚保留，18:00前可取消（特惠折扣除外）；到店付订单保留至当天18:00</view>
				</view>
				<view class="flex-row-between">
					<view class="btn btn1" @click="cancel">取消</view>
					<view class="btn btn2" @click="confirm">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import bottomPopup from "@/components/j-bottomPopup/index.vue";
	import biaofunDatetimePicker from '@/components/biaofun-datetime-picker/index.vue';
	export default {
		components: { bottomPopup, biaofunDatetimePicker },
		data() {
			return {
				themeColor: '#03004c',
				isLogin: false, // 是否已成功获取用户信息
				billInfo: {
					total: '0.00',
					discount: '0.00',
					num: 0,
					coupon: 0
				}, // 账单信息
				c_total: '', // 使用优惠券后的总金额
				// 日历
				calendar: {
					startDate: '' // 默认入住日期
				},
				// 时间
				time: {
					start: '',
					end: ''
				},
				roomName: '',// 房间名称
				// 优惠券
				coupon: {
					selected: null,
					list: []
				},
				// 支付类型
				payType: {
					value: '2',
					range: [
						{ value: '1', text: "到店支付" },
						{ value: '2', text: "线上支付" }
					]
				},
				form: {
					hotel_id: '',
					date: '',
					time: '',
					tag: '',
					day_count: '1',
					room_id: '',
					rmnum: 1,
					rsvman: '',
					mobile: '',
					channel: 'ZD',
					type: 2,
					coupon_order_id: '',
					remark: '',
					os: this.group == 'wxapp' ? 'WxApp' : 'H5'
				},
				// 支付
				h5share: true, // 当前页面是否单独获取签名
				wxSdk: false, // H5签名是否成功（此页面用于唤起支付）
				openid: null,
				wx_code: '',
			}
		},
		onLoad: function (options) {
			// 从缓存中拿取查询条件
			let JsonData = uni.getStorageSync('bookQuery')
			if (JsonData) {
				if (JsonData.calendar) {
					this.calendar = JsonData.calendar
					
					let date1 = this.$base.formatTime(new Date(JsonData.calendar.startDate), 'yyyy-MM-dd'); // 预订的日期
					let date2 = this.$base.formatTime(new Date(), 'yyyy-MM-dd'); //当天的日期
					this.form.date = date1
					this.time.end = date1 + ' 18:00'
					
					if (date1 == date2) {
						this.time.start = date1 + ' '+ this.$base.formatTime(new Date(), 'hh:mm')
					} else {
						this.time.start = date1 + ' 09:00'
					}
				}
				if (JsonData.hotel_id) {
					this.form.hotel_id = JsonData.hotel_id
				}
				if (JsonData.room_id) {
					this.form.room_id = JsonData.room_id
				}
				if (JsonData.room_name) {
					this.roomName = JsonData.room_name
				}
				if (JsonData.tag) {
					this.form.tag = JsonData.tag
				}
			}
			
			// 获取用户信息
			this.$Http({
				url: 'user',
				token: true
			}).then(res => {
				if (res.code == 1) {
					this.isLogin = true
					this.form.rsvman = res.data.user.name
					this.form.mobile = res.data.user.mobile
					
					// 获取账单
					this.getBill()
				} else {
					uni.showToast({ title: res.msg, icon: none })
				}
			});
			
			// 开启监听选择联系人
			uni.$on('chooseMan', (res) => {
				this.form.rsvman = res.name
				this.form.mobile = res.mobile
				
				// 清空选择的券
				this.coupon.selected = null
				this.form.coupon_order_id = ''
				
				// 获取账单
				this.getBill()
			})
		},
		onUnload() {
			// 关闭监听选择联系人
			uni.$off('chooseMan')
		},
		onShow() {
			// #ifdef MP-WEIXIN
			wx.login({
				success: res => {
					this.wx_code = res.code
				}
			})
			// #endif
			
			// #ifdef H5
			this.$wxapi.OnwxSdk().then(res => {
				if (res.code == 1) {
					this.wxSdk = true
					this.Onshare()
				} else {
					this.wxSdk = false
				}
			})
			this.openid = uni.getStorageSync("openid");
			// #endif
		},
		methods: {
			Ontime (date) {
				this.form.time = date.f8
			},
			// 获取下单可用的券
			getRoomCoupon () {
				this.$Http({
					url: 'roomCoupon',
					token: true,
					data: {
						room_id: this.form.room_id,
						price: this.billInfo.total,
						type: this.payType.value == '1' ? '20' : '10',
						channel: '2'
					}
				}).then(res => {
					if(res.code == 1) {
						this.coupon.list = res.data
					}
				});
			},
			// 打开优惠券
			openCoupon () {
				this.$refs.coupon.Onopen()
			},
			//使用优惠券
			Onreduce(e) {
				let list = this.coupon.list
				list.forEach(item => {
					if (item.id == e.id) {
						//不使用
						if (e.choois) {
							item.choois = false
							this.coupon.selected = null
							this.form.coupon_order_id = ''
							
							this.c_total = this.billInfo.total
							this.billInfo.discount = 0
						} else {
							//使用
							item.choois = true
							this.coupon.selected = item
							this.form.coupon_order_id = item.id
							
							let result = 0
							
							// 满减和立减
							if (item.coupon_type == 10 || item.coupon_type == 30) {
								result = this.$base.numSub(this.billInfo.total, item.reduce_money)
							}
							// 折扣
							if (item.coupon_type == 20) {
								result = this.$base.numMulti(this.billInfo.total, item.discount)
								let diff = this.$base.numSub(this.billInfo.total, result)
								item.reduce_money = diff
							}
							
							this.c_total = (result <= 0 ? '0.00' : result)
							this.billInfo.discount = item.reduce_money
						}
					} else {
						item.choois = false
					}
				})
				this.coupon.list = list
				this.$refs.coupon.onClose()
				// 强制刷新数据
				this.$forceUpdate()
			},
			// 支付方式change
			payChange(e){
				this.form.type = e.detail.value
				
				// 清空选择的券
				this.coupon.selected = null
				this.form.coupon_order_id = ''
				
				// 获取账单
				this.getBill()
			},
			// 打开明细
			openDetails () {
				this.$refs.details.Onopen()
			},
			// 备注
			Onremark (e) {
				this.form.remark = e.detail.value
			},
			// 选择联系人
			Onman () {
				uni.navigateTo({
					url: '/pages/my/contactList?mode=choose'
				});
			},
			// 获取账单
			getBill () {
				this.$Http({
					url: 'orderBill',
					token: true,
					load: true,
					data: this.form
				}).then(res => {
					if (res.code == 1) {
						this.billInfo = res.data
						
						// 下单券
						this.getRoomCoupon()
					} else {
						uni.showToast({  title: res.msg, icon: 'none' });
					}
				});
			},
			// 提交表单
			submit () {
				if (this.form.time == '') {
					uni.showToast({
						title: '请选择到店时间', icon: 'none'
					})
					return false
				}
				this.$refs.confirm.open()
			},
			// 弹窗取消
			cancel () {
				this.$refs.confirm.close()
			},
			// 弹窗确定订单
			confirm () {
				let that = this;
				
				this.$refs.confirm.close()
				this.$Http({
					url: 'orderAdd',
					type: 'POST',
					token: true,
					load: true,
					data: this.form
				}).then(res => {
					
					// 重新获取code
					// #ifdef MP-WEIXIN
					wx.login({
						success: res1 => {
							that.wx_code = res1.code
						}
					})
					// #endif
					
					if (res.code == 1) {
						// 到店支付
						if (this.payType.value == '1') {
							uni.showToast({  title: '下单成功' });
							setTimeout(()=>{
								uni.switchTab({ url: '/pages/hotel/orderList' });
							}, 2000)
						}
						// 线上支付，获取支付参数
						if (this.payType.value == '2') {
							let $obj = {
								type: 'hotel',
								order_id: res.data,
								os: this.group == 'wxapp' ? 'WxApp' : 'H5'
							}
							// #ifdef H5
							$obj.openid = this.openid
							// #endif
							// #ifdef MP-WEIXIN
							$obj.code = this.wx_code
							// #endif
							this.$Http({
								url: 'paySign',
								data: $obj,
							}).then(res1 => {
								if (res1.code == 1) {
									this.Onpay(res1.data)
								} else {
									uni.showToast({  title: res1.msg, icon: 'none' });
								}
							});
						}
					} else {
						uni.showToast({  title: res.msg, icon: 'none' });
					}
				});
			},
			// 支付
			Onpay (param) {
				var that = this
				// #ifdef MP-WEIXIN
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: param.timeStamp,
					nonceStr: param.nonceStr,
					package: param.pacKage,
					signType: 'MD5',
					paySign: param.paySign,
					success: function(res) {
						uni.showToast({  title: '支付成功' });
						setTimeout(()=>{
							uni.switchTab({ url: '/pages/hotel/orderList' })
						}, 2000)
					},
					fail: function(err) {
						uni.showToast({  title: '支付失败', icon: 'none' });
						
						// 吐券
						that.$Http({
							url: 'spit',
							token: true,
							data: {wx_order: param.order},
						}).then(res => {});
					}
				});
				// #endif
				// #ifdef H5
				if (that.wxSdk) {
					this.$wxapi.OnWXPay(param).then(res => {
						console.log('OnWXPay返回：' + JSON.stringify(res))
						if (res.code == 1) {
							uni.showToast({  title: '支付成功' });
							setTimeout(()=>{
								uni.switchTab({ url: '/pages/hotel/orderList' })
							}, 2000)
						} else if (res.code == 0) {
							uni.showToast({  title: '支付失败', icon: 'none' });
							
							// 吐券
							that.$Http({
								url: 'spit',
								token: true,
								data: {wx_order: param.order},
							}).then(res => {});
						} else if (res.code == 3) {
							uni.showToast({  title: '支付取消', icon: 'none' });
							
							// 吐券
							that.$Http({
								url: 'spit',
								token: true,
								data: {wx_order: param.order},
							}).then(res => {});
						}
					})
				} else {
					uni.showToast({  title: '微信签名失败', icon: 'none' });
				}
				// #endif
			}
		}
	}
</script>

<style lang="less">
	@import url("style.less");
</style>
